package com.example.cadmin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.cadmin.entity.Host;
import com.example.cadmin.entity.SysParamset;
import com.example.cadmin.service.HostService;
import com.example.cadmin.service.SettingService;
import com.example.cadmin.service.SysParamsetService;
import com.example.cadmin.utils.Netty.sendCmd;
import com.example.cadmin.utils.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 智能选层柜 系统设置-控制器
 * </p>
 *
 * @author 张彬
 * @since 2022-08-20
 */
@Controller
@RequestMapping("/setting")
@Slf4j
public class SettingController {
    @Resource
    private SettingService settingService;
    @Resource
    public sendCmd sendCmd;
    @Resource
    private HostService hostService;
    @Resource
    private SysParamsetService sysParamsetService;


    /**
     * 系统参数设置页面
     */
    @GetMapping("/setup/index")
    public ModelAndView setupIndex(HttpServletRequest request) {
        HttpSession session = request.getSession();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("Setting/paramsIndex");
        Map<String, Object> host = hostService.getMap(new QueryWrapper<Host>().eq("ip", session.getAttribute("cabinet")));
        int countLayer = Convert.toInt(host.get("numberOfLayers"));
        List<Object> layerList = new ArrayList<>();
        for (int layer = 1; layer <= countLayer; layer++) {
            layerList.add(layer);
        }
        modelAndView.addObject("layerList", layerList);
        modelAndView.addAllObjects(host);
        return modelAndView;
    }

    /**
     * 回到原点
     */
    @PostMapping("origin")
    @ResponseBody
    public ResponseModel origin(HttpServletRequest request) throws IOException {
        sendCmd.send("SETORIGIN:0", request, null);
        return ResponseModel.success("设置回到原点成功");
    }

    /**
     * led单独亮一列
     */
    @PostMapping("/send/led")
    @ResponseBody
    public ResponseModel sendLed(@RequestBody JSONObject data, HttpServletRequest request) {
        if (data.getInt("ledStatus") == 1) {
            if (StrUtil.isEmpty(data.getStr("ledNumber"))) {
                return ResponseModel.fail("请输入列数");
            }
            sendCmd.send("LED595:" + data.getStr("ledNumber"), request, null);
            return ResponseModel.success("第" + data.getStr("ledNumber") + "个LED亮");
        } else {
            sendCmd.send("LED595OFF:", request, null);
            return ResponseModel.success("LED灭");
        }
    }

    /**
     * LED依次亮
     */
    @PostMapping("/ledTurnsOnInTurn")
    @ResponseBody
    public ResponseModel ledTurnsOnInTurn(HttpServletRequest request) {
        sendCmd.send("LED595ON:", request, null);
        return ResponseModel.success("LED依次亮开启成功");

    }

    /**
     * 当前层 设置
     */
    @PostMapping("/layer/save")
    @ResponseBody
    public ResponseModel layerSave(@RequestBody JSONObject data, HttpServletRequest request) {
        sendCmd.send("SETLAYER:" + data.getStr("layer"), request, null);
        HttpSession session = request.getSession();
        boolean updateStatus = hostService.update(new UpdateWrapper<Host>().eq("ip", session.getAttribute("cabinet"))
                .set("currentLayer", data.getStr("layer")));
        return updateStatus ? ResponseModel.success("当前层设置成功") : ResponseModel.fail("当前层设置失败");
    }

    /**
     * 设置柜体层数
     */
    @PostMapping("/cabinetLayers/save")
    @ResponseBody
    public ResponseModel cabinetLayersSave(@RequestBody JSONObject data, HttpServletRequest request) {
        sendCmd.send("SETLAYERSNUM:" + data.getStr("numberOfLayers"), request, null);
        HttpSession session = request.getSession();
        boolean updateStatus = hostService.update(new UpdateWrapper<Host>().eq("ip", session.getAttribute("cabinet"))
                .set("numberOfLayers", data.getStr("numberOfLayers")));
        return updateStatus ? ResponseModel.success("设置柜体层数成功") : ResponseModel.fail("设置柜体层数失败");
    }

    /**
     * 设置柜体列数
     */
    @PostMapping("/cabinet/save")
    @ResponseBody
    public ResponseModel cabinetSave(@RequestBody JSONObject data, HttpServletRequest request) {
        sendCmd.send("SETROWSNUM:" + data.getStr("numberOfColumns"), request, null);
        HttpSession session = request.getSession();
        boolean updateStatus = hostService.update(new UpdateWrapper<Host>().eq("ip", session.getAttribute("cabinet"))
                .set("numberOfColumns", data.getStr("numberOfColumns")));
        return updateStatus ? ResponseModel.success("设置柜体列数成功") : ResponseModel.fail("设置柜体列数失败");
    }

    /**
     * RFID 设置
     */
    @PostMapping("/RFID/save")
    @ResponseBody
    public ResponseModel RFIDSave(@RequestBody JSONObject data, HttpServletRequest request) {
        sendCmd.send("SETRFID:" + data.getStr("RFID"), request, null);
        HttpSession session = request.getSession();
        UpdateWrapper<Host> updateWrapper = new UpdateWrapper<Host>().eq("ip", session.getAttribute("cabinet")).set("RFID", data.getStr("RFID"));
        if (data.getStr("RFID").equals("0")) {
            updateWrapper.set("real_time_read", "0");
            sendCmd.send("SETRFIDREAD:0", request, null);
        }
        boolean updateStatus = hostService.update(updateWrapper);
        return updateStatus ? ResponseModel.success("RDID设置成功") : ResponseModel.fail("RDID设置失败");
    }

    /**
     * 校准时间
     */
    @PostMapping("/datetime/save")
    @ResponseBody
    public ResponseModel datetimeSave(@RequestBody JSONObject data, HttpServletRequest request) {
        Date dateTime = data.getDate("datetime");
        String week = Convert.toStr(DateUtil.dayOfWeek(dateTime) - 1);
        String formatDateTime = DateUtil.format(dateTime, "yy/MM/dd/HH/mm/ss") + "/" + week;
        sendCmd.send("TIMING:" + formatDateTime, request, null);
        return ResponseModel.success("校准时间成功");
    }

    /**
     * 设置总脉冲数
     */
    @PostMapping("/totalNumberOfPulses/save")
    @ResponseBody
    public ResponseModel totalNumberOfPulsesSave(@RequestBody JSONObject data, HttpServletRequest request) {
        sendCmd.send("SETPULNUM:" + data.getStr("totalNumberOfPulses"), request, null);
        HttpSession session = request.getSession();
        boolean updateStatus = hostService.update(new UpdateWrapper<Host>().eq("ip", session.getAttribute("cabinet"))
                .set("totalNumberOfPulses", data.getStr("totalNumberOfPulses")));
        return updateStatus ? ResponseModel.success("设置总脉冲数成功") : ResponseModel.fail("设置总脉冲数失败");
    }

    /**
     * 设置用户密码
     */
    @PostMapping("/userPassword/save")
    @ResponseBody
    public ResponseModel userPasswordSave(@RequestBody JSONObject data, HttpServletRequest request) {
        sendCmd.send("SETPASSWORD:" + data.getStr("userPassword"), request, null);
        HttpSession session = request.getSession();
        boolean updateStatus = hostService.update(new UpdateWrapper<Host>().eq("ip", session.getAttribute("cabinet"))
                .set("userPassword", data.getStr("userPassword")));
        return updateStatus ? ResponseModel.success("设置用户密码成功") : ResponseModel.fail("设置用户密码失败");
    }

    /**
     * 重启控制器
     */
    @PostMapping("/restart/controller")
    @ResponseBody
    public ResponseModel restartController(HttpServletRequest request) {
        sendCmd.send("RST:", request, null);
        return ResponseModel.success("重启成功");
    }

    /**
     * 设置屏幕尺寸
     */
    @PostMapping("/screen/size")
    @ResponseBody
    public ResponseModel ScreenSize(@RequestBody JSONObject data, HttpServletRequest request) {
        sendCmd.send("SETLCD:" + data.getStr("setScreenSize"), request, null);
        HttpSession session = request.getSession();
        boolean updateStatus = hostService.update(new UpdateWrapper<Host>().eq("ip", session.getAttribute("cabinet"))
                .set("setScreenSize", data.getStr("setScreenSize")));
        return updateStatus ? ResponseModel.success("设置屏幕尺寸成功") : ResponseModel.fail("设置屏幕尺寸失败");
    }

    /**
     * 恢复初始密码
     */
    @PostMapping("/rest/password")
    @ResponseBody
    public ResponseModel restoreInitialPassword(HttpServletRequest request) {
        sendCmd.send("RSTPASSWORD:", request, null);
        return ResponseModel.success("恢复初始密码成功");
    }


    /**
     * 层脉冲设置
     */
    @PostMapping("/pulse/save")
    @ResponseBody
    public ResponseModel pulseSubmit(@RequestBody JSONObject data, HttpServletRequest request) {
        return settingService.pulseSubmit(data, request);
    }

    /**
     * 温湿度预警
     */
    @PostMapping("/alert/Save")
    @ResponseBody
    public ResponseModel temperatureAndHumidityWarning(@RequestBody JSONObject data, HttpServletRequest request) {
        return settingService.temperatureAndHumidityWarning(data, request);
    }

    /**
     * 调试模式
     */
    @PostMapping("/debug/save")
    @ResponseBody
    public ResponseModel debugSave(@RequestBody JSONObject data, HttpServletRequest request) {
        return settingService.debugSave(data, request);
    }

    /**
     * RFID实时读取
     */
    @PostMapping("/rfid/realtime/read/save")
    @ResponseBody
    public ResponseModel rfidRealtimeReadSave(@RequestBody JSONObject data, HttpServletRequest request) {
        return settingService.rfidRealtimeReadSave(data, request);
    }

    /**
     * 电机类型
     */
    @PostMapping("/motor/type/save")
    @ResponseBody
    public ResponseModel motorTypeSave(@RequestBody JSONObject data, HttpServletRequest request) {
        HttpSession session = request.getSession();
        UpdateWrapper<Host> updateWrapper = new UpdateWrapper<Host>().eq("number", session.getAttribute("number"));
        updateWrapper.set("motor_type", data.getStr("motor_type"));
        boolean updateStatus = hostService.update(updateWrapper);
        sendCmd.send("SETMOTORTYPE:" + data.getStr("motor_type"), request, null);
        return updateStatus ? ResponseModel.success("电机类型保存成功") : ResponseModel.fail("电机类型保存失败");
    }

    /**
     * 登录方式
     */
    @PostMapping("/login/type/save")
    @ResponseBody
    public ResponseModel loginTypeSave(@RequestBody JSONObject data, HttpServletRequest request) {
        HttpSession session = request.getSession();
        UpdateWrapper<Host> updateWrapper = new UpdateWrapper<Host>().eq("number", session.getAttribute("number"));
        updateWrapper.set("login_type", data.getStr("login_type"));
        boolean updateStatus = hostService.update(updateWrapper);
        sendCmd.send("SETLOGIN:" + data.getStr("login_type"), request, null);
        return updateStatus ? ResponseModel.success("登录方式保存成功") : ResponseModel.fail("登录方式保存失败");
    }

    /**
     * 更新参数
     */
    @PostMapping("/update/all/parameter")
    @ResponseBody
    public ResponseModel updateAllParameter(@RequestBody JSONObject data, HttpServletRequest request) {
        sendCmd.send("GETPARA:", request, null);
        return ResponseModel.success("更新参数成功");
    }


    /**
     * 电机控制方式 手动自动
     */
    @PostMapping("/motor/controller/type")
    @ResponseBody
    public ResponseModel motorControllerType(@RequestBody JSONObject data, HttpServletRequest request) {
        sendCmd.send("AUTOMANSW:" + data.getStr("motor_controller_type"), request, null);
        HttpSession session = request.getSession();
        UpdateWrapper<Host> updateWrapper = new UpdateWrapper<Host>().eq("number", session.getAttribute("number"));
        updateWrapper.set("motor_controller_type", data.getStr("motor_controller_type"));
        hostService.update(updateWrapper);
        return data.getStr("motor_controller_type").equals("1") ? ResponseModel.success("切换手动成功") : ResponseModel.success("切换自动成功");
    }

    /**
     * 系统 ip表格
     */
    @GetMapping("/host/ip/list")
    @ResponseBody
    public Map<String, Object> hostIpList(@RequestParam(value = "page") int page,
                                          @RequestParam(value = "limit") int limit) {
        return settingService.hostIpList(page, limit);
    }

    /**
     * 系统IP表格修改
     *
     * @param hostId
     * @return
     */
    @GetMapping("/host/edit")
    public ModelAndView hostEdit(@RequestParam int hostId) {
        Map<String, Object> host = hostService.getMap(new QueryWrapper<Host>().eq("id", hostId));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("Setting/host-edit");
        modelAndView.addAllObjects(host);
        return modelAndView;
    }

    /**
     * 主机IP信息修改保存
     *
     * @param data
     * @return
     */
    @PostMapping("/host/edit/save")
    @ResponseBody
    public ResponseModel hostEditSave(@RequestBody JSONObject data) {
        return settingService.hostEditSave(data);
    }

    /**
     * 主机IP信息删除
     *
     * @return
     */
    @DeleteMapping("/host/remove/{id}")
    @ResponseBody
    public ResponseModel hostRemoveId(@PathVariable("id") String id) {
        return settingService.hostRemoveId(id);
    }

    /**
     * 系统表格 机柜添加
     *
     * @return
     */
    @GetMapping("/host/add")
    public ModelAndView hostAdd() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("Setting/host-add");
        return modelAndView;
    }

    /**
     * 系统表格 机柜添加保存
     *
     * @param data
     * @return
     */
    @PostMapping("/host/add/save")
    @ResponseBody
    public ResponseModel hostAddSave(@RequestBody JSONObject data) {
        return settingService.hostAddSave(data);
    }

    /**
     * 高拍仪设置保存
     *
     * @param data
     * @return
     */
    @PostMapping("/altimeter/save")
    @ResponseBody
    public ResponseModel altimeterSave(@RequestBody JSONObject data) {
        boolean status = sysParamsetService.update(new UpdateWrapper<SysParamset>().eq("param_name", "Altimeter").set("param_value", data.getStr("altimeter")));
        return status ? ResponseModel.success("高拍仪保存成功") : ResponseModel.fail("高拍仪保存失败");
    }
}
